﻿/* This is the map coord picker button and app for django admins.
** It will look for and initialize all ids containing id_item_coords.
** It will place a map coord button next to the input and open a map
** so you can pick map cords in order to make a polyline.  It stores
** the input as ; delimited of comma separated lat lng values
** ** requires MapLayer ** */

mapl.classes.MapCoordPicker = new Class({
	multi:null,
	coordBox:null,
	input:null,
	openButton:null,
	closeButton:null,
	toolBox:null,
	map:null,
	startButton:null,
	stopButton:null,
	searchBox:null,
	clickBox:null,
	size:401,
	coords:[],
	initialize:function(el,_multi){
		this.input = el;
		this.multi = _multi
		this.coordBox = new Element('div',{class:'coord-picker',styles:{position:'relative'}}).inject(el,'before');
		var inputBox = new Element('div').inject(this.coordBox);
		el.inject(inputBox);
		// Build Buttons
		if(!this.multi){
			this.setId = el.id.substring(11,el.id.length);
		}
		var str = this.multi?'Path':'Location';
		this.openButton = new Element('input',{class:'coord-picker-open',type:'button',value:'Open '+str+' Picker',styles:{'margin-left':10}}).inject(inputBox);
		this.closeButton = new Element('input',{class:'coord-picker-close',type:'button',value:'Close '+str+' Picker',styles:{'margin-left':10,display:'none'}}).inject(this.openButton,'after');
		this.openButton.addEvent('click',this.openPicker.bind(this));
		this.closeButton.addEvent('click',this.closePicker.bind(this));
	},
	openPicker:function(){
		if(!this.toolBox){
			this.buildPicker();
		}
		this.toolBox.setStyles({'display':'block',opacity:0,top:this.openButton.getPosition().y+this.openButton.offsetHeight,left:this.openButton.getPosition().x});
		new Fx.Morph(this.toolBox,{duration:500,transition: Fx.Transitions.Cubic.easeOut,}).start({opacity:1});
		this.openButton.setStyle('display','none');
		this.closeButton.setStyle('display','inline');
		this.readCoords();
		this.renderCoords();
	},
	closePicker:function(){
		new Fx.Morph(this.toolBox,{duration:500,transition: Fx.Transitions.Cubic.easeOut,})
		.addEvent('complete',function(){this.toolBox.setStyle('display','none')}.bind(this))
		.start({opacity:0});
		this.openButton.setStyle('display','inline');
		this.closeButton.setStyle('display','none');
	},
	buildPicker:function(){
		this.toolBox = new Element('div',{styles:{width:this.size,position:'absolute',zindex:10,opacity:0}}).inject($$('body')[0]);
		var map = new Element('div',{styles:{width:this.size,height:this.size,border:'2px solid black','margin-bottom':5},class:'imap',id:'coord-picker-'+this.input.id}).inject(this.toolBox);
		new Element('div',{class:'imap-config'}).set('text','{autopin:false,zoomLevel:3,lat:38,lng:-95}').inject(map);
		this.startButton = new Element('input',{class:'coord-picker-start',type:'button',value:this.multi?'Draw':'Pick'}).inject(this.toolBox)
		.addEvent('click',this.startPicking.bind(this));
		this.stopButton = new Element('input',{class:'coord-picker-stop',type:'button',value:'Done',styles:{display:'none'}}).inject(this.toolBox)
		.addEvent('click',this.stopPicking.bind(this));
		new Element('input',{class:'coord-picker-clear',type:'button',value:'Clear '+(this.multi?'Path':'Point'),styles:{'margin-left':5}}).inject(this.toolBox)
		.addEvent('click',this.clearCoords.bind(this));
		this.searchBox = new Element('input',{styles:{'margin-left':30,width:155}}).inject(this.toolBox);
		new Element('input',{type:'button',value:'Find',styles:{'margin-left':5}}).inject(this.toolBox)
		.addEvent('click',this.findLocation.bind(this));
		if(!this.multi){
			this.searchBox.value = this.input.value;
		}
		mapl.domInit(this.toolBox);
		this.map = mapl.maps['coord-picker-'+this.input.id];
		if(!this.multi && this.input.value != '' && $('id_latitude'+this.setId).value == '' && $('id_longitude'+this.setId).value == ''){
			this.findLocation();
		}else if(!this.multi && $('id_latitude'+this.setId).value != '' && $('id_longitude'+this.setId).value != ''){
			this.map.setCenterZoom([$('id_latitude'+this.setId).value,$('id_longitude'+this.setId).value],14);
		}
	},
	startPicking:function(){
		this.startButton.setStyle('display','none');
		this.stopButton.setStyle('display','inline');
		this.clickBox = new Element('div',{styles:{
			width:this.size,height:this.size,position:'absolute','z-index':11,border:'2px solid red',top:0,left:0,cursor:'crosshair'
		}}).inject(this.toolBox)
		.addEvent('click',function(e){
			var pos = this.clickBox.getPosition();
			var x = e.page.x - pos.x - 2;
			var y = e.page.y - pos.y - 2;
			if(this.multi){
				this.coords.push(this.map.map.fromContainerPixelToLatLng({x:x,y:y}));
			}else{
				this.coords = this.map.map.fromContainerPixelToLatLng({x:x,y:y});
			}
			this.renderCoords();
		}.bind(this));
	},
	stopPicking:function(){
		this.startButton.setStyle('display','inline');
		this.stopButton.setStyle('display','none');
		this.clickBox.dispose();
	},
	findLocation:function(){
		if(this.multi){
			this.map.goToAddr(this.searchBox.value,14);
		}else{
			this.map.map.clearOverlays();
			this.input.value = this.searchBox.value;
			this.map.geocodeAddr(this.searchBox.value,function(point){
				this.map.setCenterZoom([point.lat(),point.lng()],14);
				this.coords = new GLatLng(point.lat(),point.lng());
				this.renderCoords();
			}.bind(this));
		}
	},
	clearCoords:function(){
		if(this.multi){
			this.input.value = '';
		}else{
			$('id_latitude'+this.setId).value = '';
			$('id_longitude'+this.setId).value = '';
		}
		this.readCoords();
		this.renderCoords();
	},
	renderCoords:function(){
		this.map.map.clearOverlays();
		if(this.multi){
			var str = '';
			this.coords.each(function(latLng){
				str += (Math.round(latLng.lat()*1000000)/1000000)+','+(Math.round(latLng.lng()*1000000)/1000000)+';';
			});
			this.input.value = str;
			this.map.map.addOverlay(new GPolyline(this.coords, '#0000dd', 2));
		}else{
			if(this.coords){
				$('id_latitude'+this.setId).value = Math.round(this.coords.lat()*1000000)/1000000;
				$('id_longitude'+this.setId).value = Math.round(this.coords.lng()*1000000)/1000000;
				this.map.addPin([this.coords.lat(),this.coords.lng()]);
			}else{
				$('id_latitude'+this.setId).value = '';
				$('id_longitude'+this.setId).value = '';
			}
		}
	},
	readCoords:function(){
		this.coords = [];
		if(this.multi){
			this.input.value.split(';').each(function(coord){
				var latLng = coord.split(',');
				if(latLng.length == 2){
					this.coords.push(new GLatLng(latLng[0],latLng[1]));
				}
			}.bind(this));
		}else{
			if($('id_latitude'+this.setId).value != '' && $('id_longitude'+this.setId).value != ''){
				this.coords = new GLatLng( parseFloat( $('id_latitude'+this.setId).value ), parseFloat( $('id_longitude'+this.setId).value ) );
			}else{
				this.coords = null;
			}
		}
	}
});

window.addEvent('domready',function(){
	var init = function(root){
		root.getElements('.map-multi-select').each(function(s){
			new mapl.classes.MapCoordPicker(s,true);
		});
		root.getElements('.map-single-select').each(function(s){
			new mapl.classes.MapCoordPicker(s,false);
		});
	}
	this.addDomInit(init);
	init(document);
}.bind(mapl));